import { createRouter, createWebHistory } from 'vue-router';
import LoginView from '@/view/LoginView.vue';
import RegisterView from '@/view/RegisterView.vue';
import DataView from '@/view/DataView.vue';

const routes = [
    {
        path: '/',
        redirect: '/login', // 默认跳转到登录页
    },
    {
        path: '/login',
        name: 'login',
        component: LoginView,
    },
    {
        path: '/register',
        name: 'register',
        component: RegisterView,
    },
    {
        path: '/data',
        name: 'data',
        component: DataView,
        meta: { requiresAuth: true }, // 需要登录才能访问
    },
];

const router = createRouter({
    history: createWebHistory(),
    routes,
});

// 路由守卫：检查用户是否登录
router.beforeEach((to, from, next) => {
    const isAuthenticated = localStorage.getItem('token'); // 从本地存储中获取 token
    if (to.meta.requiresAuth && !isAuthenticated) {
        next('/login'); // 未登录则跳转到登录页
    } else {
        next();
    }
});

export default router;